

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #    填写   企业参与国家标准或行业标准制定情况汇总表
import re

from lxml import etree

from PageObjectRequests import base_url
from util import http_utils
from util.pdfSplit.compress_pdf import CompressPdf
from util.pdfSplit.pdf_split import get_file_oss
from util.selenium.webdriver.common.by import By
from base.BaseMethod import BM
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.g import g


class WriteStandForm():
    form_btn_loc = (By.LINK_TEXT, '企业参与国家标准或行业标准制定情况汇总表')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")
    #    添加按钮
    # add_btn_loc = (By.CSS_SELECTOR, '.form-group.pull-right .blue')
    add_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '添加')]")
    #    删除按钮
    # delete_btn_loc = (By.CSS_SELECTOR, '.table-search div:nth-of-type(2) button')
    delete_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '删除')]")
    standard_name_loc = (By.CSS_SELECTOR, 'input#bname')
    standard_num_loc = (By.CSS_SELECTOR, 'input#bnumber')
    # 标准级别 字典值 standard_level
    level = ''
    level_css_str = 'input#dataEprTotalForm_dataEprTotal_blevel'
    # 参与方式 字典值 prtp_mode
    way = ''
    way_css_str = 'input#dataEprTotalForm_dataEprTotal_pway'
    # level_loc = (By.CSS_SELECTOR, level_css_str + level)
    # way_loc = (By.CSS_SELECTOR, way_css_str + way)
    upload_btn_loc = (By.CSS_SELECTOR, '.uploadAttachment a')
    back_btn_loc = (By.CSS_SELECTOR, '.box-footer.text-right button.btn-default')
    save_btn_loc = (By.CSS_SELECTOR, '.box-footer.text-right button#dataEprTotalsave')
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 暂时不使用
    # 国家级别
    conutry_level_loc = (By.CSS_SELECTOR, 'input#dataEprTotalForm_dataEprTotal_blevel国家')
    # 行业级别
    industry_level_loc = (By.CSS_SELECTOR, 'input#dataEprTotalForm_dataEprTotal_blevel行业')
    # 参与方式 主持
    preside_over_style_loc = (By.CSS_SELECTOR, 'input#dataEprTotalForm_dataEprTotal_pway主持')
    # 参与方式 参与
    participation_style_loc = (By.CSS_SELECTOR, 'input#dataEprTotalForm_dataEprTotal_pway参与')
    ##DataEprTotal_list > div.eXtremeTable > div.page > ul > li:nth-child(4) > a
    next_page_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(4) a")

    page_num_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(3) a")
    select_all_loc = (By.CSS_SELECTOR, "input#items_selector")

    delete = False
    # 写代码时方便提示, 基本方法完成后删除
    # driver = driver
    def __init__(self, driver=None):
        self.driver = driver
        self.size = 2
        self.flag = False
        setattr(g, self.class_name, list())

    def get_level_loc(self):
        return (By.CSS_SELECTOR, self.level_css_str + self.level)

    def get_way_loc(self):
        return (By.CSS_SELECTOR, self.way_css_str + self.way)

    @property
    def class_name(self):
        return self.__class__.__name__

    def click_save_btn(self):
        return BM.global_click_btn(btn_loc=self.save_btn_loc, driver=self.driver)

    @FormDataDecorator
    def main(self, id='', stand_name='', stand_num='', stand_level='', stand_way='', oss_path=None):
        try:
            stand_name = stand_name.replace(" ","").replace("\\xa", "")
            stand_num = stand_num.replace(" ", "").replace("\\xa", " ")
            class_name = self.class_name
            li_list = getattr(g, class_name)
            if not self.flag:
                # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
                ele = BM.get_ele(driver=self.driver, ele_loc=self.form_btn_loc, time=6)
                detail_url = ele.get_attribute("href")
                if not g.all_optimized:
                    BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
                BM.get_cookie(driver=self.driver)
                detail_url = detail_url if detail_url.startswith("https://") else \
                    base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            if not self.flag:
                res = None
                self.flag = True
                while True:
                    if not res:
                        res = http_utils.send_get(detail_url, driver=self.driver)
                    text = res.get("text")
                    # 替换掉国网随机插入的字符串
                    random_insert_chars_p = ".*?([\r\n].[0-9a-zA-Z]{4,}[\r\n].).*?"
                    res = re.findall(random_insert_chars_p, text, re.S)
                    for i in res:
                        text = text.replace(i, "")
                    tree = etree.HTML(text)
                    # 获取 已上传记录
                    tr_list = tree.xpath(
                        '//form[@id="DataEprTotal_list"]//div[@class="tableRegionDivBody"]//tbody/tr')
                    for tr in tr_list:
                        stand_num_str = BM.get_first(tr.xpath("./td[5]/text()"))
                        stand_name_str = BM.get_first(tr.xpath("./td[3]/text()"))
                        sign_str = "{}:{}".format(stand_name_str, stand_num_str)
                        print(sign_str)
                        li_list.append(sign_str)

                    # 匹配下一页 url
                    next_list = tree.xpath("//form[@id='DataEprTotal_list']//div[@class='page']/ul/li[4]/a")
                    next_a = BM.get_first(next_list)
                    next_onclick = None if not next_a else next_a.attrib.get("onclick")
                    if not next_onclick:
                        break
                    else:
                        # 获取下一页url
                        next_url_pattern = """.*?setAttribute\(['|"]action['|"],'(.*?)'.*?"""
                        next_res = re.findall(next_url_pattern, next_onclick, re.S)
                        next_url = BM.get_first(next_res)
                        next_page_pattern = """.*?value=['|"](\d+)['|"];.*?"""
                        next_page_res = re.findall(next_page_pattern, next_onclick, re.S)
                        next_page = BM.get_first(next_page_res)
                        if not next_url or not next_page:
                            break
                        next_url = (base_url + next_url) if not next_url.startswith("https://") else next_url
                        query_data = {
                            "ec_i": "",
                            "DataEprTotal_list_crd": "10",
                            "DataEprTotal_list_p": next_page,
                            "DataEprTotal_list_a_dataEprTotal_bname": "",
                            "DataEprTotal_list_a_dataEprTotal_blevel": "",
                            "DataEprTotal_list_a_dataEprTotal_bnumber": "",
                            "DataEprTotal_list_a_dataEprTotal_pway": "",
                            "dataInnocomId": "",
                            "type": "",
                            "DataEprTotal_list_rd": "10",
                        }
                        tree = etree.HTML(text)
                        query_data["ec_i"] = BM.get_first(tree.xpath("//input[@name='ec_i']/@value"))
                        query_data["DataEprTotal_list_a_dataEprTotal_bname"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprTotal_list_a_dataEprTotal_bname']/@value"))
                        query_data["DataEprTotal_list_a_dataEprTotal_blevel"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprTotal_list_a_dataEprTotal_blevel']/@value"))
                        query_data["DataEprTotal_list_a_dataEprTotal_bnumber"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprTotal_list_a_dataEprTotal_bnumber']/@value"))
                        query_data["DataEprTotal_list_a_dataEprTotal_pway"] = BM.get_first(tree.xpath(
                            "//input[@name='DataEprTotal_list_a_dataEprTotal_pway']/@value"))
                        query_data["dataInnocomId"] = BM.get_first(tree.xpath("//input[@name='dataInnocomId']/@value"))
                        query_data["type"] = BM.get_first(tree.xpath("//input[@name='type']/@value"))
                        res = http_utils.send_post(next_url, data=query_data, driver=self.driver)

            sign = "{}:{}".format(stand_name, stand_num)
            if sign in li_list:
                g.logger.info("{} 已存在".format(sign))
                return
            # 获取标准详情页
            add_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/addOrUpdateDataEprTotal.do"
            add_res = http_utils.send_post(url=add_url, driver=self.driver)
            token = add_res.get("token")
            text = add_res.get("text")

            save_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveDataEprTotal.do"
            data = {
                "dataEprTotal.id": "",
                "dataInnocom.id": "",
                "curYear": "",
                "dataEprTotal.dataId": "",
                "dataId": "",
                "struts.token.name": "token",
                "token": token,
                "dataEprTotal.bname": stand_name,
                "dataEprTotal.blevel": stand_level,
                "dataEprTotal.bnumber": stand_num,
                "dataEprTotal.pway": stand_way
            }
            tree = etree.HTML(text)
            data["dataEprTotal.id"] = BM.get_first(tree.xpath("//input[@name='dataEprTotal.id']/@value"))
            data["dataInnocom.id"] = BM.get_first(tree.xpath("//input[@name='dataInnocom.id']/@value"))
            data["curYear"] = BM.get_first(tree.xpath("//input[@name='curYear']/@value"))
            data["dataEprTotal.dataId"] = BM.get_first(tree.xpath("//input[@name='dataEprTotal.dataId']/@value"))
            data["dataId"] = BM.get_first(tree.xpath("//input[@name='dataId']/@value"))

            file_path = None
            if g.need_file:
                if oss_path:
                    file_path = BM.get_material_path() + "\\STD\\std_{}.pdf".format(id)
                    is_exist = BM.check_file(file_path=file_path, size=self.size)
                    if is_exist is True:
                        oss_file = get_file_oss(oss_path=oss_path, local_path=file_path + ".pdf")
                        BM.wait_file(file_path=oss_file)
                        CompressPdf(file_path=oss_file, max_size=self.size).compress()
                        BM.wait_file(file_path=file_path)

            res = http_utils.send_post(url=save_url, data=data, file_path=file_path,
                                       file_key="upload", driver=self.driver)
            text = res.get("text")
            message = res.get("message")
            g.logger.info("企业参与国家标准或行业标准制定情况汇总表（{}）上传结果: {}".format(sign, message))
            if u"成功" in message:
                li_list.append(sign)
        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(
                err, err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)
